<template>
  <div class="publish-page">
    <el-card>
      <div slot="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>发布文章</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-form label-width="120px" :rules="rules" :model="form" ref="form">
        <el-form-item label="标题：" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入文章标题"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item label="频道：" prop="channel_id">
          <ChannelList
            :newArr="channelList"
            v-model="form.channel_id"
          ></ChannelList>
        </el-form-item>
        <el-form-item label="封面：" prop="cover">
          <el-radio-group v-model="form.cover.type"  @change="typeChangeFn">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <div>
            <el-upload
              v-if="form.cover.type === 1 || form.cover.type === 3"
              :action="url"
              list-type="picture-card"
              name="image"
              :limit="form.cover.type"
              :on-success="successFn"
              :on-remove="removeFn"
              :file-list="fileListFn"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="内容：" prop="content">
          <quill-editor v-model="form.content" @change="onEditorChange"></quill-editor>
        </el-form-item>
           <el-form-item label="" v-if="$route.query.id">
          <el-button type="primary" @click="onEditFn(false)">编辑文章</el-button>
          <el-button @click="onEditFn(true)">存入草稿</el-button>
        </el-form-item>
        <el-form-item label="" v-else>
          <el-button type="primary" @click="onSubmitFn(false)">发布文章</el-button>
          <el-button @click="onSubmitFn(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getChannelAPI, setArticleAPI, getOneArticleAPI, editArticleAPI } from '@/api'
import { imgUrl } from '@/utils/global'
import ChannelList from '@/components/ChannelList.vue'
export default {
  name: 'PublishPage',
  components: {
    ChannelList
  },
  data () {
    return {
      // 表单数据
      form: {
        title: null,
        content: null,
        cover: {
          type: 1,
          images: []
        },
        channel_id: null
      },
      channelList: [],
      url: imgUrl,
      richText: '',
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'change', min: 5, max: 15 }
        ],
        channel_id: [
          { required: true, message: '请选择频道', trigger: 'change' }
        ],
        cover: [
          {
            required: true,
            message: '请选择图片',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (value.type === 1 && value.images.length === 1) {
                callback()
              } else if (value.type === 3 && value.images.length === 3) {
                callback()
              } else if (value.type < 1) {
                callback()
              } else {
                callback(new Error('请输入正确数量的图片'))
              }
            }
          }
        ],
        content: [
          {
            required: true,
            message: '请选择内容',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.richText.length >= 10 && this.richText.length < 100) {
                callback()
              } else {
                callback(new Error('请输入10-100个字'))
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    fileListFn () {
      return this.form.cover.images.map((url, index) => {
        return {
          name: index + 'jpg',
          url: url

        }
      })
    }
  },
  methods: {
    // 提交文章事件
    onSubmitFn (bool) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          console.log('验证成功')
          await setArticleAPI({
            draft: bool,
            ...this.form
          })
          this.$router.push('/layout/article')
        } else {
          return false
        }
      })
    },
    onEditFn (bool) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          console.log('验证成功')
          console.log(this.$route.query.id)
          await editArticleAPI({
            id: this.$route.query.id,
            draft: bool,
            ...this.form
          })
          this.$router.push('/layout/article')
        } else {
          return false
        }
      })
    },
    // 图片切换验证事件
    typeChangeFn () {
      if (this.form.cover.type >= 1 && this.form.cover.images.length > 0) {
        this.form.cover.images = [this.form.cover.images[0]]
      } else {
        this.form.cover.images = []
      }
      this.$refs.form.validateField('cover')
    },
    // 富文本验证的文字
    onEditorChange ({ quill, html, text }) {
      this.richText = text.replace(/\n/, '')
      this.$refs.form.validateField('content')
    },
    // 图片上传成功时的钩子
    successFn (file) {
      //   console.log(file)
      this.form.cover.images.push(file.data.url)
      this.$refs.form.validateField('cover')
    },
    // 图片删除成功时的钩子
    removeFn (file) {
      //   console.log(file)
      const ind = this.form.cover.images.findIndex((str) => {
        return str === file.url
      })
      this.form.cover.images.splice(ind, 1)
      this.$refs.form.validateField('cover')
    }
  },
  async created () {
    const res = await getChannelAPI()
    this.channelList = res.data.data.channels
    const id = this.$route.query.id
    if (id) {
      const res1 = await getOneArticleAPI(id)
      //   console.log(res1)
      this.form = res1.data.data
    }
  }
}
</script>

<style scoped lang='less'>
/deep/ .ql-editor {
  height: 250px;
}
</style>
